package com.bobi.tfca.ui.mainnavigation.user.member

import android.app.AlertDialog
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.MemberAPI
import com.bobi.tfca.network.response.MemberResponse
import com.bobi.tfca.util.LogUtil
import com.bobi.tfca.viewmodel.PublicViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class MemberManageFragmentVM : ViewModel() {

    val members by lazy {
        MutableLiveData(ArrayList<MemberResponse>())
    }

    fun findAllLeaveMembers(
        publicViewModel: PublicViewModel,
        memberLeaveFragment: MemberLeaveFragment
    ) {
        publicViewModel.apply {
            request(MemberAPI::class.java).findAllLeaveMembers().getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val result = it.data?.data
                                if (result != null) {
                                    members.value = result
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fun findAllStillMembers(
        publicViewModel: PublicViewModel,
        memberStillFragment: MemberStillFragment
    ) {
        publicViewModel.apply {
            request(MemberAPI::class.java).findAllStillMembers().getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val result = it.data?.data
                                if (result != null) {
                                    members.value = result
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fun searchStillMemberByName(publicViewModel: PublicViewModel, searchContent: String, fragment: Fragment) {
        publicViewModel.apply {
            request(MemberAPI::class.java).searchStillMemberByName(searchContent).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val result = it.data?.data
                                if (result != null) {
                                    members.value = result
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fun searchLeaveMemberByName(publicViewModel: PublicViewModel, searchContent: String, fragment: Fragment) {
        publicViewModel.apply {
            request(MemberAPI::class.java).searchLeaveMemberByName(searchContent).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val result = it.data?.data
                                if (result != null) {
                                    members.value = result
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fun removeAssMember(
        publicViewModel: PublicViewModel,
        memberStillFragment: MemberStillFragment,
        memberId: Int
    ) {
        publicViewModel.apply {
            request(MemberAPI::class.java).removeAssMember(memberId).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val code = it.data?.code
                                if (code == 200) {
                                    // 再次查询人数
                                    findAllStillMembers(publicViewModel, memberStillFragment)
                                    Toast.makeText(memberStillFragment.requireActivity(), "移除成功", Toast.LENGTH_SHORT).show()
                                } else {
                                    Toast.makeText(memberStillFragment.requireActivity(), "移除失败", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fun getAllRoles(
        publicViewModel: PublicViewModel,
        fragment: MemberStillFragment,
        clickedMemberId: Int
    ) {
        publicViewModel.apply {
            request(MemberAPI::class.java).getAllRoles().getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val result = it.data?.data
                                if (result != null) {
                                    var alertDialog2: AlertDialog? = null
                                    val items : Array<String> = result.map { item -> item.position }.toTypedArray()
                                    // TODO 这里可以优化为默认选择的是当前会员的角色
                                    var selectRole : Int = 0
                                    val alertBuilder = AlertDialog.Builder(fragment.requireActivity())
                                    alertBuilder.setTitle("更改职位")
                                    alertBuilder.setSingleChoiceItems(
                                        items, 0
                                    ) { dialogInterface, i ->
                                        selectRole = i
                                    }

                                    alertBuilder.setPositiveButton(
                                        "确定"
                                    ) { dialogInterface, i ->
                                        run {
                                            LogUtil.i("选择的职位------${items[selectRole]}")
                                            // 修改职位
                                            this@MemberManageFragmentVM.changeMemberRole(publicViewModel, fragment, items[selectRole], clickedMemberId)
                                            alertDialog2?.dismiss()
                                        }
                                    }

                                    alertBuilder.setNegativeButton(
                                        "取消"
                                    ) { dialogInterface, i -> alertDialog2?.dismiss() }

                                    alertDialog2 = alertBuilder.create()
                                    alertDialog2.show()
                                }
                            }
                        }
                    }
                }
            }
        }

    }

    private fun changeMemberRole(
        publicViewModel: PublicViewModel,
        fragment: MemberStillFragment,
        role: String,
        clickedMemberId: Int
    ) {
        publicViewModel.apply {
            request(MemberAPI::class.java).changeMemberRole(clickedMemberId, role).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val code = it.data?.code
                                if (code == 200) {
                                    Toast.makeText(fragment.requireActivity(), "修改成功", Toast.LENGTH_SHORT).show()
                                    // 再次查询人数
                                    findAllStillMembers(publicViewModel, fragment)
                                } else {
                                    Toast.makeText(fragment.requireActivity(), "修改失败", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}